import { listDevices, sleep } from './utils';
import { WebContents } from 'electron';
import { AndroidDevice } from '@/main/adb/android-device';

export class DeviceMonitor {
  /**
   * 向渲染进程发送消息
   */
  sender: WebContents;
  /**
   * 设备列表
   */
  devices: AndroidDevice[] = [];
  private _stoped = true;

  constructor(sender: WebContents) {
    this.sender = sender;
  }

  async run() {
    if (this._stoped) {
      return;
    }

    const devices = await listDevices();

    if (devices.length !== this.devices.length) {
      // 两者长度不一致, 说明插入电脑的设备数量发生变化
      this.devices = devices;
      this.sendToRenderer();
    } else {
      if (devices.length > 0) {
        // 判断设备ID和设备状态是否发生改变
        let hasChange = false;

        for (const device of devices) {
          const finded = this.devices.find(d => d.id === device.id);
          // 新读取到的设备不存在上一次读到的设备列表中,或者设备状态发生改变了
          if (!finded || finded.status !== device.status) {
            hasChange = true;
            break;
          }
        }

        if (hasChange) {
          this.devices = devices;
          this.sendToRenderer();
        }
      }
    }

    await sleep(600);
    await this.run();
  }

  private sendToRenderer() {
    this.sender.send('devices', this.devices);
  }

  start() {
    if (this._stoped) {
      this._stoped = false;
      (async () => this.run())();
    }
  }

  stop() {
    this._stoped = true;
  }
}
